package com.book.common.api.helper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Description：通过反射获取国际化对象，调用国际化语言方法，主要针对FeignClient的api
 *
 * @Author： leo.xiong
 * @CreateDate： 2020/07/14 10:28
 * @Email： leo.xiong@suyun360.com
 * @Since：
 */
public class LanguageHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(LanguageHelper.class);

    private static ApplicationContext applicationContext;
    /**
     * 获取国际化方法
     */
    private static Method method;

    private static Object i18nHelper;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (LanguageHelper.applicationContext == null) {
            LanguageHelper.applicationContext = applicationContext;
        }
    }

    public static void init() {
        if (applicationContext != null && method == null) {
            synchronized (LanguageHelper.class) {
                if (method == null) {
                    try {
                        LanguageHelper.i18nHelper = LanguageHelper.applicationContext.getBean("i18nHelper");
                        LanguageHelper.method = LanguageHelper.i18nHelper.getClass().getDeclaredMethod("getStringDefaultValue", String.class, String.class, String.class);
                    } catch (Exception e) {

                    }
                }
            }
        }
    }

    public static String getValue(String key) {
        return getStringDefaultValue(key, null);
    }

    public static String getValue(String key, String placeholderValue) {
        return getStringDefaultValue(key, null);
    }

    public static String getStringDefaultValue(String key, String defaultValue) {
        if (LanguageHelper.i18nHelper == null) {
            synchronized (LanguageHelper.class) {
                init();
            }
        }
        if (method == null) {
            return getValue(null, key, defaultValue);
        }
        Object value = null;
        try {
            value = LanguageHelper.method.invoke(LanguageHelper.i18nHelper, key, defaultValue);
        } catch (IllegalAccessException | InvocationTargetException e) {
            LOGGER.warn("获取国际化数据异常：", e);
        } finally {
            return getValue(value, key, defaultValue);
        }
    }

    private static String getValue(Object value, String key, String defaultValue) {
        if (value == null) {
            if (StringUtils.isEmpty(defaultValue)) {
                return key;
            } else {
                return defaultValue;
            }
        } else {
            return value.toString();
        }
    }
}
